package com.wyl.idempotentcheck.common;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisService {
    private Logger logger = LoggerFactory.getLogger(RedisService.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将key存入缓存，并设置超时时间
     * @param key
     * @param value
     * @param timeout
     */
    public void set(String key, String value, long timeout) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 根据Key查询缓存中的数据
     * @param key
     * @return
     */
    public String get(final String key){
        if (ObjectUtil.isEmpty(key)) {
            logger.warn("获取Redis缓存，传入的Key为空");
            return null;
        }
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 根据key删除缓存数据
     * @param key
     */
    public void delete(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 查询缓存是否存在
     * @param encode
     * @return
     */
    public boolean checkForm(String encode,long timeOut){
        String key = get(encode);
        //若存在该key则返回true
        if (ObjectUtil.isNotEmpty(key)){
            return true;
        }
        set(encode, IdUtil.randomUUID(), timeOut);
        return false;
    }

}
